<template>
    <view class="pdf-preview">
        <iframe id="iframe" :style="workflowHeight" border="0" frameborder="0" src="" width="100%"></iframe>
        <!-- <view style="width: 100vw;height: 100vh;" class="html_model" v-html="html"></view> -->
        
        
        <view v-if="html" class="html_model" style="width: 100vw; height: 100vh" v-html="highlightedContent"></view>
        <u-icon v-if="search == true" class="icon" color="#2979ff" name="arrow-left" size="28"
                @click="rightPopup"></u-icon>
        <u-popup :show="show" mode="right" @close="closeFn" @open="openFn">
            <view v-for="(item, index) in items" :key="index" :class="knowledgeIndex == index ? 'active' : ''"
                  class="model" @click="knowledgeFn(item, index)">
                <text> 关键字片段{{ index + 1 }}</text>
                <text>{{ item.text }}</text>
            </view>
        </u-popup>
    </view>
</template>

<script>
export default {
    name: 'preview',
    data() {
        return {
            show: false,
            knowledgeIndex: -1,
            info: {},
            defaultCourseUrl: '',
            defaultFlag: false,
            isSearch: false,
            QA: false,
            html: null,
            items: [],
            search: false,
            keywords: []
        }
    },
    /*onLoad(options) {
        console.log(options, '查看进入的参数')
        this.info = JSON.parse(decodeURIComponent(options.info))
        this.isSearch = options.isSearch
        this.search = options.search == 'true' ? true : false
        if (this.search == true) {
            this.items = this.info.ext.items
            this.keywords = this.info.ext.items[0].text.split(',')
            this.knowledgeIndex = 0
        }
        console.log(options.search, this.info, 'ffffff')
        this.QA = options.QA
        
        this.getPreview()
    },*/
    computed: {
        workflowHeight() {
            let height = document.documentElement.clientHeight || document.body.clientWidth
            height = (height - 46) * 2
            return {
                height: height + 'rpx'
            }
        },
        highlightedContent() {
            // this.html = "<p>code fff废物范围</p>"
            let content = this.html
            this.keywords.forEach((keyword) => {
                const regex = new RegExp(keyword, 'g')
                content = content.replace(regex, (match) => {
                    return `<span class="highlight">${match}</span>`
                })
            })
            setTimeout(() => {
                this.scrollToElement()
            }, 100)
            
            return content
        }
    },
    methods: {
        init(obj) {
            this.$modal.loading('正在加载中···')
            console.log("查看参数", 'init', obj)
            this.info = obj ? obj.info : {}
            this.defaultCourseUrl = obj ? obj.defaultCourseUrl : ''
            this.defaultFlag = obj ? obj.defaultFlag : false
            if (this.defaultFlag) {
                if (this.defaultCourseUrl) {
                    let iframe = document.querySelector('#iframe')
                    this.populateIframe(iframe, [['token', +uni.getStorageSync('token')]], uni.$config.baseUrl + this.defaultCourseUrl)
                }
            } else {
                this.getPreview()
            }
        },
        scrollToElement() {
            this.$nextTick(() => {
                const element = document.querySelector('.highlight')
                if (element) {
                    element.scrollIntoView({
                        behavior: 'smooth',
                        block: 'center'
                    })
                }
            })
        },
        rightPopup() {
            console.log('ffff')
            this.show = true
        },
        closeFn() {
            this.show = false
        },
        openFn() {
            // this.show = false
        },
        knowledgeFn(item, index) {
            this.knowledgeIndex = index
            this.keywords = item.text.split(',')
            console.log('knowledge', this.keywords, index)
        },
        getPreview() {
            // this.$modal.loading('正在加载中···')
          this.$request({
              url: `/file/preview/getHtmlUrl`,
              method: 'get',
              params:{
                id:this.info.id
              }
      })
        .then(({ data }) => {
          // 处理 ReadableStream 数据
          if(!data.readAuthority){
                this.$toast(data.message)
                return
              }
              let iframe = document.querySelector("#iframe");
              this.populateIframe(iframe, [["token", +uni.getStorageSync("token")]], uni.$config.baseUrl + data.downloadUrl);
        })
        .catch((error) => {
          // 处理错误
          console.error("Error:", error);
        });
        },
        populateIframe(iframe, headers, url) {
            let xhr = new XMLHttpRequest()
            xhr.open('GET', url)
            xhr.responseType = 'blob'
            headers.forEach((header) => {
                xhr.setRequestHeader(header[0], header[1])
            })
            xhr.onreadystatechange = () => {
                if (xhr.readyState === xhr.DONE) {
                    console.log(window.location.href.split('#')[0], '5555')
                    if (xhr.status === 200) {
                        if (this.isSearch) {
                            this.$modal.closeLoading()
                            // iframe.src = window.location.href.split("#")[0]+'/static/pdfjs/web/viewer.html?keyword=工艺数据&file=' + URL.createObjectURL(
                            // 	xhr.response)
                            this.html = xhr.response
                        } else {
                            this.$modal.closeLoading()
                            console.log(xhr, 'fff6666')
                            iframe.src = window.location.href.split('#')[0] + '/static/pdfjs/web/viewer.html?file=' + URL.createObjectURL(xhr
                                    .response)
                            // this.html = xhr.response;
                        }
                    }
                }
            }
            xhr.send()
            /*getDocument.promise.then(() => {
                      })
                      
                      let url = 'path/to/your/pdf.pdf';
                      PDFJS.getDocument(url).promise.then(function(pdf) {
                          console.log('PDF内容加载完成')
                          this.$modal.closeLoading()
                      }).catch(function(error) {
                          console.error('加载PDF时发生错误: ', error)
                      })*/
        }
    }
}
</script>

<style lang="scss">
.html_model {
    padding: 20rpx;
    
    ::v-deep h1 {
        font-size: 32rpx !important;
        padding: 30rpx 0 20rpx !important;
    }
    
    ::v-deep h2 {
        font-size: 30rpx !important;
        padding: 30rpx 0 20rpx !important;
    }
    
    ::v-deep h3 {
        font-size: 28rpx !important;
        padding: 30rpx 0 20rpx !important;
    }
    
    ::v-deep p {
        line-height: 40rpx !important;
        font-size: 28rpx;
        font-weight: 400;
    }
    
    ::v-deep p:nth-child(1) {
        font-size: 36rpx;
        font-weight: 550;
        padding: 30rpx;
        text-align: center;
    }
    
    ::v-deep img {
        width: 94.5vw;
        // height: 940rpx;
        // margin-left: 25vw;
        padding: 20rpx 0;
    }
    
    ::v-deep table {
        border-collapse: collapse;
        /* 合并单元格边框 */
        // border: 1px solid #ddd; /* 设置表格边框 */
        width: 96vw;
        display: flex;
        overflow-x: scroll;
    }
    
    ::v-deep tr {
        width: auto;
        border: 1px solid #ddd;
        /* 设置单元格边框 */
        padding: 8rpx;
        /* 设置单元格内边距 */
    }
    
    ::v-deep td {
        width: auto;
        border: 1px solid #ddd;
        /* 设置单元格边框 */
        padding: 10rpx;
        /* 设置单元格内边距 */
        color: #1c2126;
        font-size: 24rpx;
    }
    
    ::v-deep tr td:nth-child(1) {
        font-size: 28rpx;
        font-size: 500;
        width: 140rpx;
        display: block;
        background: #eaecef;
        color: #1c2126;
    }
    
    ::v-deep td p {
        white-space: nowrap;
    }
}

.icon {
    width: 80rpx;
    height: 80rpx;
    border: 1rpx solid #ccc;
    border-radius: 50%;
    display: flex;
    // justify-content: center;
    align-items: center;
    position: fixed;
    right: -25rpx;
    top: 50%;
    z-index: 999;
    background: white;
}

.html_model ::v-deep .highlight {
    background-color: yellow;
    font-weight: bold;
    display: inline-block;
}

.model {
    width: 400rpx;
    border: 1rpx solid #ccc;
    padding: 10rpx 5rpx;
    margin: 5rpx;
    
    text {
        display: block;
        
        &:nth-child(1) {
            font-weight: 550;
            border-bottom: 1rpx solid #ccc;
            padding: 5rpx 0;
        }
    }
}

.active {
    background: #67deb2;
    color: #fff;
}
</style>
